import 'package:dio/dio.dart';
import 'dart:convert' as convert;
import '/common/global.dart';

class CustomInterceptor extends Interceptor {
  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    String tokenName = Global.api.tokenKeyName;
    String? token = await Global.store.getData(tokenName);
    if (null != token) {
      options.headers[tokenName] = token;
    }
    handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    Global.log.debug("Request OK! ----> result: $response ");
    Map<String, dynamic> resp = convert.jsonDecode(response.toString());
    int code = resp["code"];
    String msg = resp["msg"];
    if (code == 200) {
      handler.next(response);
    } else if (code == 600) {
      Global.log.error("not auth! ----> message: $msg ");
      handler.reject(
          DioException(message: msg, requestOptions: response.requestOptions));
    } else if (code == 500) {
      Global.log.error("business excepton! ----> message: $msg ");
      handler.reject(
          DioException(message: msg, requestOptions: response.requestOptions));
    }
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    Global.log.error("Request Error! ----> [${err.message}]");
    return handler.resolve(Response(
      data: "请求失败",
      requestOptions: err.requestOptions,
    ));
  }
}
